import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
let timer = null; // 定时器
class Toast {
  static info (msg, timeout) {
    msg = msg || 'info'; // 提示信息
    timeout = timeout || 2000; // 显示的时长
    init();
    setTime(timeout);
    ReactDOM.render(<span className="info">{msg}</span>, document.getElementById('toast'))
  }
  static danger (msg, timeout) {
    msg = msg || 'danger'; // 提示信息
    timeout = timeout || 2000; // 显示的时长
    init();
    setTime(timeout);
    ReactDOM.render(<span className="danger">{msg}</span>, document.getElementById('toast'))
  }
}

function init () {
  // 清除定时器
  clearTimeout(timer);
  // 找到DOM节点
  let toast = document.getElementById('toast');
  if (toast) { // 如果DOM节点存在
    toast.style.display = 'block';
  } else {
    // DOM节点不存在 ----  创建DOM节点，添加到页面中
    let div = document.createElement('div');
    div.setAttribute('id', 'toast');
    document.body.appendChild(div);
  }
}

function setTime (timeout) {
  timer = setTimeout (() => {
    let toast = document.getElementById('toast');
    if (toast) {
      toast.style.display = 'none';  
    }
  }, timeout)
}

export default Toast;
